<?php
/**
 * 飞信机器人--功能插件--开心辞典
 * 功能：仿开心辞典答题闯关类
 *      当前，每答对一题送1分
 *      答错n题后，自动终止，用户可以按 r 键，重新加始新一轮挑战（分数清0）
 * 数据表：fx_articles(存放题目，选项用|分隔，正确的答案后面加X)
 *                    如： 天鹅|娃娃鱼|孔雀|丹顶鹤X，丹顶鹤X 为正确答案 
 *        fx_game_kaixincidian_records：存放答题记录
 *        fx_game_kaixincidian_scores: 用户的分数
 * 		  fx_winners： 存储中奖人用户飞信号码
 * 作者： Kelvin
 * 联系： msn:shichangguo@msn.com, qq:191848423
*/
/*
支持参数(fx_menus表 extra_params字段)：
classid=分类id，
action=start： 开始闯关
action=queryscore：分数查询
action=iswinner: 是否中奖
log=1:是否开启log, 为1开启，当开启log后，用户每次的查询将生成log,用以统计查询
*/


class GameKaiXinCiDian extends CommonPlugin
{
	var $UUID='4ddaef64-64ad-4f9a-8734-f179f68658f1';
	var $maxError = 0;	// =0, disable
	var $scorePerQuestion = 1;
	var $resetEnable = false;
	
	public function GameKaiXinCiDian(&$session, $pid, $extraPara="")
	{
		parent::__construct($session, $pid, $extraPara);
	}
	
	private function setQuestionID($class_id,$question_id)
	{
		$this->set("{$class_id}_qid", $question_id);
	}

	private function getQuestionID($class_id)
	{
		$id = $this->getValue("{$class_id}_qid");
		return $id;
	}
	
	public function queryscore($class_id)
	{	
		return "您的当前分数：".$this->getScore($class_id)."\n"."系统最高分数:".$this->getMaxScore($class_id)."\n".$this->getFooter();	
	}
	
	
	function decode139($rec)
	{
		//return $rec['C'];
		$key = '$des@139';
		$iv = '12345qaz';
		
		$fid = $rec['F'];
		$cardencoded = base64_decode($rec['C']);
		$crc = $rec['V'];
		
		$card = mcrypt_decrypt(MCRYPT_DES, $key, $cardencoded, MCRYPT_MODE_CBC, $iv);
		$card = rtrim($card, "\0");
		
		if($card===false)
			return "解密错误";
		
		$verify = md5($fid.$card);
		
		if($verify==$crc)
			return $card;
		else
			return "Error on md5";
	}
	
	function queryResult139($event_id,$fetion_no)
	{
		// S=fetion@139com
		// VSTR=md5（fid ＋ md5（pid ＋ S））

		$vstr = md5($fetion_no.md5($event_id.'fetion@139com'));
		$queryURL = "http://u.co-cm.com/frbt/s.php?fid={$fetion_no}&pid={$event_id}&vs={$vstr}";
		
		//file_put_contents("/var/wwwroot/fetion.zhaoxuefeng.com/log.html",$queryURL."<br/>\n",FILE_APPEND);
		
		$xml = file_get_contents($queryURL);
		
		$p = xml_parser_create();
		xml_parse_into_struct($p, $xml, $valsArr, $indexArr);
		xml_parser_free($p);
		
		ob_start();
		echo($xml);
		$decodeXML = ob_get_contents();
		ob_end_clean();
		//file_put_contents("/var/wwwroot/fetion.zhaoxuefeng.com/log.html",htmlspecialchars($decodeXML)."<br/>\n",FILE_APPEND);
		
		//if(in_array($fetion_no,array('769236303','294737020','801504505','768611336')))
		{
			$buddy_id = $this->getBuddyID();
			$create_time = time(NULL);
			$content = mysql_real_escape_string($decodeXML);
			
			$sql = "insert into fx_winner_139log(buddy_id,create_time,response) values({$buddy_id},{$create_time},'$content')";
			$this->execute($sql);
		}
		
		$retV = 0;
		$retD = "";
		$retRecs = array();
		
		for($i=0; $i<count($valsArr); $i++)
		{
			if( $valsArr[$i]['type'] != 'complete' )continue;
			
			switch($valsArr[$i]['tag'])
			{
				case 'V':$retV = $valsArr[$i]['value'];
								 break;
				case 'D':$retD = $valsArr[$i]['value'];
								 break;
				case 'I':$retRecs[] = $valsArr[$i]['attributes'];
			}
		}
		
		// 如果错误，直接返回错误信息
		if( intval($retV) < 0 )
		{
			return $retD;
		}
		
		if(count($retRecs)==0)return "很抱歉，您没有中奖，谢谢您的关注与支持！";
		
		/*
	       [F] => fetionno2  飞信号
	       [P] => pid2  活动号
	       [M] => m2    手机号
	       [C] => card2  充值卡密码
	       [V] => crc2   校验码
	       [D] => date2  日期
		*/
		$msg = '';
		$flag = false;
		for($i=0; $i<count($retRecs); $i++)
		{
			if( $retRecs[$i]['P'] == $event_id && $retRecs[$i]['F'] == $fetion_no )
			{
				$msg.="中奖日期:".$retRecs[$i]['D']." 充值卡密码:" . $this->decode139($retRecs[$i]) ."\n";
				$flag = true;
			}
		}
		
		
		/*ob_start();
		echo $fetion_no."==".$eventid."\n";
		print_r($retRecs);
		return ob_get_contents();
		ob_end();*/
		
			
		if(!$flag)return "很抱歉，您没有中奖，谢谢您的关注与支持！";
		return $msg;
	}

	public function isWinner139()
	{
		$event_id = $this->extraParam['eventid'];
		
		$fetion_no = $this->getBuddyFetion();
		
		//if(in_array($fetion_no,array('769236303','294737020','801504505','768611336')))
		//{
			return $this->queryResult139($event_id,$fetion_no)."\n".$this->getFooter();
		//}
		//return "不要着急哦，请耐心等待，每周一公布上周的中奖名单，请稍后再查询。".$this->getFooter();
	}
	public function getTips()
	{
		$class_id = $this->extraParam['classid'];
		$action = $this->extraParam['action'];
		
		if( $action == 'iswinner139')return $this->isWinner139();
		if( $action == 'iswinner')return $this->isWinner($class_id);
		if( $action == 'queryscore')return $this->queryscore($class_id);
		
		return $this->newQuestion($class_id);
	}

	public function showQuestion($class_id, $question)
	{
		$msg = $question['title']."\n";
		$arr = explode('|', $question['content']);
	
		for($i=0; $i<count($arr); $i++)
		{
			$msg.='['.($i+1).'] '.str_replace('X','',$arr[$i])."\n";
		}
		return $msg;
	}
	
	public function getScore($class_id)
	{
		$sql = "select * from fx_game_kaixincidian_scores where buddy_id={$this->getBuddyID()} and class_id={$class_id}";
		$result = $this->query($sql);
		if(count($result)==0) return 0;
		
		return $result[0]['score'];	
	}
	
	public function getMaxScore($class_id)
	{
		$sql = "select max(score) as score from fx_game_kaixincidian_scores where class_id={$class_id}";
		$result = $this->query($sql);
		
		if(count($result)==0)return "无记录";
		
		return $result[0]['score'];		
	}
	public function newQuestion($class_id)
	{	
		if( $this->maxError>0)
		{
			//查看是否已经错过 maxError 题目, result=0：答错
			$sql = "select count(*) as count from fx_game_kaixincidian_records where buddy_id={$this->getBuddyID()} and class_id={$class_id} and result=0";
			$result = $this->query($sql);
			if( $result[0]['count'] > $this->maxError )
			{
				$maxScore = $this->getMaxScore($class_id);
				$myScore = $this->getScore($class_id);
				
				if($this->resetEnable)
				{
					return "您已经错过{$this->maxError}次，本轮答题结束。系统最高分数--{$maxScore},您的得分--{$myScore}。您可以选择 r, 开始新的一轮挑战！".$this->getFooter(' r-重新挑战');
				}else
				{
					return "您已经错过{$this->maxError}次，本轮答题结束。系统最高分数--{$maxScore},您的得分--{$myScore}。".$this->getFooter();					
				}
			}
		}
			
		//查看用户是否有尚未答过的题目
		$questionID = $this->getQuestionID($class_id);
		if($questionID != 0 )
		{
			$sql = "select * from fx_game_kaixincidian_records where buddy_id={$this->getBuddyID()} and article_id=$questionID";
			$result = $this->query($sql);
			if( count($result) == 0 )
			{
				$sql = "select * from fx_articles where id=$questionID";
				$result = $this->query($sql);
				if($this->resetEnable)
				{
					return "<b>继续您上次的答题</b>:)\n".$this->showQuestion($class_id, $result[0]). $this->getFooter(',数字键--答题 r-重新挑战');
				}else
				{
					return "<b>继续您上次的答题</b>:)\n".$this->showQuestion($class_id, $result[0]). $this->getFooter(',数字键--答题');
				}
			}
		}
		//选出用户已经答过的题目
		$buddyID = $this->getBuddyID();
		$sql = "select article_id from fx_game_kaixincidian_records where buddy_id={$buddyID} and class_id={$class_id}";
		$result = $this->query($sql);
		//print_r($result);
		
		$cond = "";
		$num = count($result);
		for($i=0; $i<$num; $i++)
		{
			$cond .= $result[$i]['article_id'];
			if( $i!=($num-1) ) $cond.=",";
		}
		if($cond != "" )
		{
			$cond = " id not in($cond)";
		}
		
		//随机抽题
		$sql = "select * from fx_articles where class_id=$class_id";
		if($cond!="")$sql.=" and $cond";
		
		$sql .= " order by rand() limit 1";
		
		//echo $sql;
		
		$result = $this->query($sql);
		
		if(count($result) == 0 )
		{
			return "恭喜您，您已答完所有题目，真乃达人也，等着抽奖吧，Good Luck！\n".$this->getFooter($this->resetEnable?' r-重新挑战':"");
		}
		
		$this->setQuestionID($class_id, $result[0]['id']);
		
		return $this->showQuestion($class_id, $result[0]). $this->getFooter($this->resetEnable?',数字键--答题 r-重新挑战':',数字键--答题');
	}
	private function getCurrentVote($class_id,$inc=0)
	{
		$buddy_id = $this->getBuddyID();
		$sql = "select count(*) as count from fx_game_kaixincidian_records where buddy_id={$buddy_id} and result=1";
		
		$retArr = $this->query($sql);
		$count = $retArr[0]['count']+$inc;
		
		if($count>=3)
		{
			return "您已经答对{$count}题， 已经具备抽奖资格了!答对的题目越多，中奖几率越大哦！";
		}
		if($count==0)
		{
			return "您需要答对3道题，才具备抽奖资格！答对的题目越多，中奖几率越大哦！";	
		}
		
		$left = 3-$count;
		return "您还需要答对{$left}道题，才具备抽奖资格!答对的题目越多，中奖几率越大哦！";
	}
	public function doQuestion($class_id,$input)
	{
		$needLog = $this->extraParam['log']-1==0;
		
		$input = intval($input);
		$questionID = $this->getQuestionID($class_id);
		
		$sql = "select * from fx_articles where id=$questionID";
		$result = $this->query($sql);
		if( count($result) == 0 )
		{
			return "系统错误，未发现该题目！".$this->getFooter();
		}
		
		$arr = explode('|', $result[0]['content']);
		if( $input<1 || $input > count($arr) )
		{
			return "输入错误，请重新选择".$this->getFooter();
		}
		
		$optionID = $input;
		$question = $arr[$input-1];
		
		$time = time(NULL);
		$buddyID = $this->getBuddyID();
		
	
		$question = str_replace("\n","",$question);
		$question = str_replace("\r","",$question);
		$question = trim($question);
		
		if( substr($question, -1) == 'X')
		{
			// 正确
			$value = 1;
			$msg = "恭喜，您的回答正确！\n\n<font color=\"red\">".$this->getCurrentVote($class_id,1)."</font>\n\n<font color=\"green\">继续下一题目！</font>\n\n";
			// 加分
			$sql = "select * from fx_game_kaixincidian_scores where buddy_id={$buddyID} and class_id={$class_id}";
			$result = $this->query($sql);
			if(count($result)==0)
			{
				$this->execute("insert into fx_game_kaixincidian_scores(buddy_id,class_id,score) values($buddyID,$class_id,{$this->scorePerQuestion})");
			}else 
			{
				$this->execute("update fx_game_kaixincidian_scores set score=score+1 where buddy_id=$buddyID and $class_id=$class_id");
			}
		}else
		{
			$value = 0;
			if( $this->maxError>0 )
			{
				$msg = "您的回答错误，最多可以错{$this->maxError}次！<font color=\"green\">继续下一题目！</font>\n\n";
			}else 
			{
				$msg = /*ord(substr($question, -1)).":".$question.*/ "您的回答错误，\n\n<font color=\"red\">".$this->getCurrentVote($class_id)."</font>\n\n<font color=\"green\">继续下一题目！</font>\n\n";
			}			
		}
		
		if( $needLog )
		{
			$aid = $questionID;
			$sql = "update fx_articles set click=click+1 where id=$aid";
			$this->execute($sql);
			//$msg.=$sql."\n";
			$time = time(NULL);
			$buddyid = $this->getBuddyID();
			$sql = "insert into fx_log_articles(buddy_id,article_id,create_time) values($buddyid,$aid,$time)";
			$this->execute($sql);
			//$msg.=$sql."\n";
		}
		
		$sql = "insert into fx_game_kaixincidian_records(buddy_id,class_id,article_id,option_id,add_time,option_value,result)";
		$sql.= " values($buddyID,$class_id,$questionID,$optionID,$time,'{$question}',$value)";
		//$msg.=$sql;
		$this->execute($sql);

		//清空题目记录
		$this->setQuestionID($class_id,0);	
		return $msg.$this->newQuestion($class_id);
	}
	
	public function isWinner($class_id)
	{
		$fetion_no = $this->getBuddyFetion();
		
		$sql = "select count(*) as count from fx_winners where event_id={$class_id}";
		$retArrs = $this->query($sql);
		$count = $retArrs[0]['count'];
			
		$sql = "select * from fx_winners where fetion_no='{$fetion_no}' and event_id={$class_id}";
		$retArrs = $this->query($sql);
		
		$msg = "";
		if(count($retArrs) == 1 )
		{
			$what = $retArrs[0]['what'];
			$msg = "恭喜您，您中奖了，奖品为 \"{$what}\"，领奖办法请查看上级菜单中的活动详情。";
			$id =  $retArrs[0]['id'];
			$time = time(NULL);
			$sql = "update fx_winners set query_time={$time} where id={$id}";
			$this->execute($sql);
		}else if ( $count == 0 )
		{
			if($class_id==6) // 3G 最终大奖
			{
				$msg = "不要着急哦，请耐心等待，本次活动将于6月30日之后的10个工作日内公布最终大奖的中奖名单，请稍后再查询。";
			}else if($class_id==9) // MOTO手机中奖查询
			{
				$msg = "不要着急哦，请耐心等待，每周一公布上周的中奖名单，请稍后再查询。";
			}else
			{
				$msg = "不要着急哦，请耐心等待，本次活动将于5月31日和6月30日24点各抽出在当月答对问题的50名中奖用户。抽出中奖者后10个工作日公布中奖名单，请稍后再查询。";
			}
		}else
		{
			$msg = "很抱歉，您没有中奖，谢谢您的关注与支持！";
		}
		return $msg."\n".$this->getFooter();
	}
	public function handle($input)
	{
		if( parent::handleInput($input)) return false;
					
		$class_id = $this->extraParam['classid'];
		$action = $this->extraParam['action'];

		if( $action == 'iswinner')return $this->isWinner($class_id);
		if( $action != 'start' )return "错误输入".$this->getFooter();

		if( $input == 'r' /*&& $this->resetEnable*/ )
		{
			$this->setQuestionID($class_id, 0); //清空记录
			$buddy_id = $this->getBuddyID();
			$this->execute("delete from fx_game_kaixincidian_records where buddy_id={$buddy_id} and class_id={$class_id}");
			$this->execute("update fx_game_kaixincidian_scores set score=0 where buddy_id={$buddy_id} and class_id={$class_id}");
			return $this->newQuestion($class_id);
		}
		if( is_numeric($input) )
		{
			return $this->doQuestion($class_id,$input);
		}
		return "输入错误：{$input}\n".$this->getFooter();
	}
}
?>